let OrderId = 0;
let CountExpressNum = 0;
let expNo = 0; //快递单号
let orderState = 0;
let orderListInfo = [];
layui.config({
    version: '1510164124181'
}).use(['form', 'laypage', 'layer', 'element', 'laydate'], function () {
    form = layui.form;
    layer = layui.layer;
    laypage = layui.laypage; //分页
    element = layui.element; //元素操作
    OrderId = GetQueryString("OrderId");
    if (OrderId == null || OrderId == "" || OrderId == undefined) {
        OrderId = 0;
    } else {
        $(".OrderNum").html(OrderId);
        SelectOrderListi();
    }
    //查询快递详情  为避免多次调用，每次调用一次

});

function OpenOrClose() {
    if ($(".LogisticsInfo").is(":visible")) {
        $(".LogisticsInfo").hide();
    } else {
        $(".LogisticsInfo").show();
    }
}

function SelectExpressInfo() {
    if (CountExpressNum > 0) {
        return;
    }
    $.ajax({
        url: httpurl + "/kdniaoTrack",
        cache: false,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType: 'application/json',
        data: {
            "expNo": expNo,
        },
        success: function (data) {
            CountExpressNum++;
            let status = data.showapi_res_body.status;
            let info = "";
            if (status > 1) {
                let dataInfo = data.showapi_res_body.data;

                if (dataInfo.length > 0) {
                    for (let i = 0; i < dataInfo.length; i++) {
                        info += '<li class="layui-timeline-item">' +
                            '<i class="layui-icon layui-timeline-axis">&#xe63f;</i>' +
                            '<div class="layui-timeline-content layui-text">' +
                            '<h3 class="layui-timeline-title">' + dataInfo[i].time + '</h3>' +
                            ' <p>' + dataInfo[i].context + '</p>' +
                            '</div>' +
                            '</li>';
                    }
                } else {
                    info += '<li class="layui-timeline-item">暂无数据</li>';
                }

            } else {
                let les = (status == -1 ? "待查询" : (status == 0 ? "查询异常" : (status == 1 ? "暂无记录" : "暂无记录")));
                info += '<li class="layui-timeline-item">' + les + '</li>';
                //-1 待查询 0 查询异常 1 暂无记录 2 在途中 3 派送中 4 已签收 5 用户拒签 6 疑难件 7 无效单 8 超时单 9 签收失败 10 退回
            }
            $(".LogisticsInfo ul").html(info);


        }
    });
}

function SelectOrderListi() {
    $.ajax({
        url: httpurl + "/FindOrderListId",
        cache: false,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType: 'application/json',
        data: {
            "id": OrderId,
        },
        success: function (data) {
            let info = "";
            if (data.rtnCode == 200) {

                var dataInfo = data.data;
                orderListInfo = dataInfo;
                orderState = dataInfo.state;
                expNo = dataInfo.express_num;
                let typeValue = ""
                switch (dataInfo.type) {
                    case 0:
                        typeValue = "普通订单"
                        break;
                    case 1:
                        typeValue = "秒杀"
                        break;
                    case 2:
                        typeValue = "拼团"
                        break;
                    case 3:
                        typeValue = "免费领取"
                        break;
                    case 6:
                        typeValue = "换购"
                        break;
                    case 17:
                        typeValue = "积分商品"
                        break;
                    case 16:
                        typeValue = "赠品"
                        break;
                    case 18:
                        typeValue = "显示特惠"
                        break;
                    case 19:
                        typeValue = "权益折扣"
                        break;
                    case 12:
                        typeValue = "包含多种类型订单"
                        break;
                    default:
                        break;
                }
                info += '<tr>' +
                    '<td>手机号:' + dataInfo.phone + '</td>' +
                    '<td>姓名:' + dataInfo.name + '</td>' +
                    '</tr>' +
                    '<tr>' +
                    '<td>所在地区:' + dataInfo.address + '</td>' +
                    '<td>联系电话:' + dataInfo.phone + '</td>' +
                    '</tr>' +
                    '<tr>' +
                    // '<td>订单类型:' + (dataInfo.type == 0 ? "普通订单" : (dataInfo.type == 1 ? "秒杀订单" : (dataInfo.type == 2 ? "拼单订单" : "未知"))) + '</td>' +
                    '<td>订单类型:' + typeValue + '</td>' +
                    '<td>订单金额:' + dataInfo.ordermoney + '</td>' +
                    '</tr>' +
                    '<tr>' +
                    '<td>快递公司:' + (dataInfo.express_name == null ? "无" : dataInfo.express_name) + '</td>' +
                    '<td>快递单号:' + (dataInfo.express_num == null ? "无" : dataInfo.express_num) + '</td>' +
                    '</tr>' +
                    '<tr>' +
                    '<td>下单时间:' + dataInfo.intime + '</td>' +
                    '<td>支付时间:' + dataInfo.paytime + '</td>' +
                    '</tr>' +
                    '<tr>' +
                    '<td class="text-danger">用户备注:' + (dataInfo.remark==null?"无":dataInfo.remark) + '</td>' +
                    '<td class="text-danger">客服备注:' + (dataInfo.csd==null?"无":dataInfo.csd)  + '</td>' +
                    '</tr>'+
                    '<tr>' +
                    '<td>礼盒备注:' + (dataInfo.giftRemarks==null?"":dataInfo.giftRemarks) + '</td>' +
                    '<td>待收金额:' + (dataInfo.amountCollected==null?"":dataInfo.amountCollected) + '</td>' +
                    '</tr>'
                    ;
                $(".orderInfo").html(info);
                GoodsDetails(dataInfo);
                // alert(orderState+"===="+(orderState>1 || orderState==0));
                if (orderState > 1) {
                    //如果快递待发货，则不调用 SelectExpressInfo();
                    SelectExpressInfo();
                }
                if (orderState == 6) { //订单为备货状态，才能发货
                    $(".sendExpress").show();
                }


                //处理状态时间线
                DetaileStateTime(orderState);
            }

        }
    });
}

function DetaileStateTime(state) {
    //let time_line_box=["待付款","待发货","备货中","待收货","已收货","售后","取消"];
    let time_line_box_state = [0, 1, 6, 2, 3, 4, 5];
    let scalexs = [0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80];
    let indexOf = time_line_box_state.indexOf(state);
    let findLen = $(".time_line_box ol").find("li");
    let scalex = 1;
    if (indexOf < findLen.length) {
        scalex = scalexs[indexOf] + 0.05;
    }
    for (let i = 0; i <= indexOf; i++) {
        $(findLen[i]).find(".order_item").addClass("selected");

    }
    $(".filling_line").css("transform", "scaleX(" + scalex + ")");
}

function GoodsDetails(dataInfo) {
    let orderList = dataInfo.orderInfo;
    let dataHtml = "";
    let allPayPoints = ''
    let tempCouponDefalut = (dataInfo.couponRecord == null ? "" : (dataInfo.couponRecord.couponEntity == null ? "该优惠券不存在了" : (dataInfo.couponRecord.couponEntity.name + ":" + dataInfo.couponRecord.couponEntity.val + "元")));
    let tempCoupon = ''
    for (let a = 0; a < orderList.length; a++) {
        let ostate = (dataInfo.state == 0 ? '待付款' : (dataInfo.state == 1 ? '待发货' : (dataInfo.state == 2 ? '待收货' : (dataInfo.state == 3 ? '已收货' : (dataInfo.state == 4 ? '售后' : (dataInfo.state == 5 ? '已取消' : ((dataInfo.state == 6 ? '待备货' : "未知"))))))));
        let paypoints = ''
        if (orderList[a].fromType == 1) {
            tempCoupon = ''
        } else if (orderList[a].fromType == 17) {
            tempCoupon = ''
            if (orderList[a].infoPayIntegral) {
                paypoints = `<br/><span style="color:#d88795">+${orderList[a].infoPayIntegral}积分</span>`
            }
        } else {
            tempCoupon = tempCouponDefalut
            if(orderList[a].integralDeductedProportion!=0){
                tempCoupon+=`<div>使用了${dataInfo.integralWhiteGive}积分抵扣${dataInfo.integralDeductedMoney}金额（抵扣比例${dataInfo.integralDeductedProportion}%）</div>`
            }
        }
        dataHtml += '<tr class="item border-dashed">' +
            '<td class="s-title">' +
            '<a href="#" class="J_MakePoint">' +
            '<img src="' + visitimgurl + '/' + (orderList[a].productEntity == null ? "" : orderList[a].productEntity.headimg) + '" class="itempic"><span class="title J_MakePoint">' + orderList[a].pname + '</span></a>' +
            '<div class="props">' +
            '<span>套餐: ' + orderList[a].mname + ' </span>' +
            '<span>数量: ' + orderList[a].num + ' </span>' +
            '</div>' +
            '<a title="消费者保障服务，卖家承诺商品如实描述" href="#" target="_blank">' +
            '<img src="http://img03.taobaocdn.com/tps/i3/T1bnR4XEBhXXcQVo..-14-16.png"/>' +
            '</a>' +
            '<div>' +
            '<span style="color:gray;">卖家承诺72小时内发货</span>' +
            '</div>' +
            '</td>' +
            '<td>' + orderList[a].mname + '</td>' +
            '<td>' + ostate + '</td>' +
            '<td>￥' + orderList[a].price + paypoints + '</td>' +
            '<td>' + orderList[a].num + '</td>' +
            '<td>' + tempCoupon + '</td>' +
            '<td>￥' + parseFloat(orderList[a].price * orderList[a].num).toFixed(2) + '</td>' +
            '<td>' +
            '<span>￥' + orderList[a].freight + '</span><br/>' +
            '</td>' +
            '</tr>';
    }
    if (dataInfo.orderIntegral) {
        allPayPoints = `<div style="font-size:14px">共消耗积分：<span style="color:#d88795">${dataInfo.orderIntegral}</span></div>`
    }
    dataHtml += '<tr>' +
        '<td colspan="7"></td>' +
        `<td style="text-align:right">
            <div style="font-size:20px;">商品总价：<span style="color:red;">${dataInfo.ordermoney}</span></div>
            ${allPayPoints}
        </td>`+
        '</tr>';
    $(".ProductDetaileTable tbody").html(dataHtml);
    goods_detail(dataInfo);
}

function goods_detail(dataInfo) {
    let info = '<tr>' +
        '<td>收货地址:</td>' +
        '<td>' + dataInfo.name + "," + dataInfo.phone + "," + dataInfo.address + '</td>' +
        '</tr>' +
        '<tr>' +
        '<td>运送方式:</td>' +
        '<td>快递</td>' +
        '</tr>' +
        '<tr>' +
        '<td>物流公司名称:</td>' +
        '<td>' + (dataInfo.express_name == null ? "无" : dataInfo.express_name) + '</td>' +
        '</tr>' +
        '<tr>' +
        '<td>运单号:</td>' +
        '<td>' + (dataInfo.express_num == null ? "无" : dataInfo.express_num) + '</td>' +
        '</tr>' +
        '<tr>' +
        '<td colspan="2" class="text-success" onclick="OpenOrClose();">物流运送详情</td>' +
        '</tr>';
    $("#goods_detail thead").html(info);
}

function updateRemark() {
    // console.log(JSON.stringify(orderListInfo));
    layer.open({
        type: 1,
        area: ['500px', '600px'],
        shadeClose: false, //点击遮罩关闭
        content: '<form class="am-form" style="width: 80%;margin: 0 auto;">' +
            '<br><br>' +
            '<div class="form-group-col-2">' +
            '<div class="form-label" style="max-width: 120px">收货人姓名：</div>' +
            '<div class="form-cont" style="margin-left: 120px;">' +
            '<input id="unames" type="text" class="form-control width100 form-boxed" value="' + orderListInfo.name + '"  placeholder="收货人姓名" />' +
            '</div>' +
            '</div>' +
            '<div class="form-group-col-2">' +
            '<div class="form-label" style="max-width: 120px">收货人电话：</div>' +
            '<div class="form-cont" style="margin-left: 120px;">' +
            '<input id="uphones" type="text" class="form-control width100 form-boxed"  value="' + orderListInfo.phone + '"  placeholder="联系电话" />' +
            '</div>' +
            '</div>' +
            '<div class="form-group-col-2">' +
            '<div class="form-label" style="max-width: 120px">所在地区：</div>' +
            '<div class="form-cont" style="margin-left: 120px;">' +
            '<input id="uaddress" type="text" class="form-control width100 form-boxed"  value="' + orderListInfo.address + '"  placeholder="所在地区" />' +
            '</div>' +
            '</div>' +
            '<div class="form-group-col-2">' +
            '<div class="form-label" style="max-width: 120px">快递公司：</div>' +
            '<div class="form-cont" style="margin-left: 120px;">' +
            '<input id="uexpress_name" type="text" class="form-control width100 form-boxed"  value="' + (orderListInfo.express_name == null ? "" : orderListInfo.express_name) + '"  placeholder="快递公司" />' +
            '</div>' +
            '</div>' +
            '<div class="form-group-col-2">' +
            '<div class="form-label" style="max-width: 120px">快递单号：</div>' +
            '<div class="form-cont" style="margin-left: 120px;">' +
            '<input id="uexpress_num" type="text" class="form-control width100 form-boxed"  value="' + (orderListInfo.express_num == null ? "" : orderListInfo.express_num) + '"  placeholder="快递单号" />' +
            '</div>' +
            '</div>' +
            '<div class="form-group-col-2">' +
            '<div class="form-label" style="max-width: 120px">待收金额：</div>' +
            '<div class="form-cont" style="margin-left: 120px;">' +
            '<input id="amountCollected" type="number" class="form-control width100 form-boxed"   value="' + (orderListInfo.amountCollected == null ? "" : orderListInfo.amountCollected) + '"  placeholder="待收金额"></input>' +
            '</div>' +
            '</div>' +
            '<div class="form-group-col-2">' +
            '<div class="form-label" style="max-width: 120px">订单备注：</div>' +
            '<div class="form-cont" style="margin-left: 120px;">' +
            '<textarea id="csd" type="text" class="form-control width100 form-boxed"   value=""  placeholder="订单备注">' +  (orderListInfo.csd == null ? "" : orderListInfo.csd) + '</textarea>' +
            '</div>' +
            '</div>' +
            '<div class="form-group-col-2">' +
            '<div class="form-label" style="max-width: 120px">礼盒备注：</div>' +
            '<div class="form-cont" style="margin-left: 120px;">' +
            '<textarea id="giftRemarks" type="text" class="form-control width100 form-boxed"   value=""  placeholder="礼盒备注">' + (orderListInfo.giftRemarks == null ? "" : orderListInfo.giftRemarks) + '</textarea>' +
            '</div>' +
            '</div>' +
            '<div class="flex flex-wrap flex-col-3">' +
            '<div class="form-group-col-2">' +
            '<div class="form-label"></div>' +
            '<div class="form-cont">' +
            '<input type="button" onclick="sureUpdate()" value="确认"  class="btn btn-info"/>&nbsp;&nbsp;' +
            '<input type="button" onclick="closeAllLayer()" value="取消" class="btn btn-danger"/>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</form>'
    });
}

function closeAllLayer() {
    layer.closeAll();
}

function sureUpdate() {
    let uname = $("#unames").val();
    let uphone = $("#uphones").val();
    let address = $("#uaddress").val();
    let express_name = $("#uexpress_name").val();
    let express_num = $("#uexpress_num").val();
    let csd = $("#csd").val();
    let amountCollected = $("#amountCollected").val();
    let giftRemarks = $("#giftRemarks").val();
    let remark = "";
    top.layer.confirm('确认提交？', { icon: 3, title: '提示信息' }, function (index) {
        var index = top.layer.msg('提交中，请稍候', { icon: 16, time: false, shade: 0.8 });
        $.ajax({
            type: "POST",
            url: httpurl + "/updateOrderList", //修改订单信息
            cache: false,
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "*",
                "Access-Control-Allow-Headers": "Authorization",
                "Authorization": GetTokenInfo()
            },
            contentType: 'application/json',
            data: JSON.stringify({
                "id": OrderId,
                "name": uname,
                "phone": uphone,
                "address": address,
                "express_name": express_name,
                "express_num": express_num,
                "remark": remark,
                "csd": csd,
                "giftRemarks":giftRemarks,
                "amountCollected":amountCollected
            }),
            success: function (data) {
                layer.closeAll();
                top.layer.msg(data.msg);
                location.reload();
            },
            error:(err)=>{
                top.layer.msg('待收金额只能为数字');
            }
        });
    }, function () {

    });
}

function UpdateOrderEntity() {
    layer.open({
        type: 1,
        area: ['500px', '300px'],
        shadeClose: false, //点击遮罩关闭
        content: '<form class="am-form" style="width: 80%;margin: 0 auto;">' +
            '            <br><br>' +
            '            <label for="username" style="font-size: 20px;">快递公司:</label>' +
            '            <input type="text" name="name" id="express_name" style="width: 70%;height: 30px;"/>' +
            '            <br><br><br>' +
            '            <label for="username" style="font-size: 20px;">快递单号:</label>' +
            '            <input type="text" name="username" id="express_num" style="width: 70%;height: 30px;"/>' +
            '            <br><br><br><br>' +
            '            <div class="flex flex-wrap flex-col-3">' +

            '<div class="form-group-col-2">' +
            '<div class="form-label"></div>' +
            '<div class="form-cont">' +
            '<input type="button" onclick="SendOrderInfo()" value="确认"  class="btn btn-info"/>&nbsp;&nbsp;' +
            '<input type="button" onclick="re()" value="取消" class="btn btn-danger"/>' +

            '</div>' +
            '</div>' +
            '</div>' +
            '        </form>'
    });
}

function SendOrderInfo() {
    let express_name = $("#express_name").val();
    let express_num = $("#express_num").val();
    top.layer.confirm('确认提交？', { icon: 3, title: '提示信息' }, function (index) {
        var index = top.layer.msg('提交中，请稍候', { icon: 16, time: false, shade: 0.8 });
        $.ajax({
            type: "POST",
            url: httpurl + "/SendOrderInfoExpress",
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "*",
                "Access-Control-Allow-Headers": "Authorization",
                "Authorization": GetTokenInfo()
            },
            contentType: 'application/json',
            cache: false,
            data: JSON.stringify({
                "orderid": OrderId,
                "express_name": express_name,
                "express_num": express_num
            }),
            success: function (data) {
                layer.closeAll();
                top.layer.msg(data.msg);
                re();
            }
        });
    }, function () {

    });
}

function re() {
    window.history.go(-1);
}